package edu.pku.sei.transformation.codegen;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;

import edu.pku.sei.transformation.editor.model.AtomicTransformation;
import edu.pku.sei.transformation.editor.model.execution.TransformationExecution;
import edu.pku.sei.transformation.editor.model.implement.ICodegenElement;
import edu.pku.sei.transformation.editor.model.implement.TransformationCode;

public abstract class AtomicTransformationCodegenAdapter extends CodegenAdapter {
	@Override
	public boolean canGenerate(ICodegenElement element) {
		if (element != null) {
			if (element instanceof AtomicTransformation)
				return true;
			else if (element instanceof TransformationExecution) {
				TransformationExecution transExe = (TransformationExecution) element;
				if (transExe.getTransformation() != null && transExe.getTransformation() instanceof AtomicTransformation)
					return true;
				else
					return false;
			} else 
				return false;
		} else {
			return false;
		}
	}
	
	public AtomicTransformation getAtomicTransformation(ICodegenElement element) {
		if (!canGenerate(element))
			return null;
		else if (element instanceof AtomicTransformation)
			return (AtomicTransformation) element;
		else if (element instanceof TransformationExecution)
			return (AtomicTransformation) ((TransformationExecution)element).getTransformation();
		else
			return null;
	}

	@Override
	public boolean generateCode(ICodegenElement element, boolean force) {
		if (!canGenerate(element)) {
			return false;
		} else {
			AtomicTransformation transformation = getAtomicTransformation(element);
			
			IFile file = null;
			TransformationCode code = transformation.getCode(getLanguage());
			
			//already have code
			if (code != null && code.getFile() != null) {
				file = code.getFile();
				//force generate
				if (force) {
					return generateCodeToFile(element, file);
				} else {
					return true;
				}
			} 
			//do not have code
			else {
				try {
					file = getFile(transformation, getFileName(element), getLanguage());
					if (file == null)
						return false;
				} catch (CoreException e1) {
					e1.printStackTrace();
					return false;
				}
				
				IPath projPath = file.getProject().getLocation();
				IPath path = file.getLocation();
				if(projPath.isPrefixOf(path)) {
					path = new Path(path.toString().substring(projPath.toString().length()));
				}
				
				code = transformation.addCode(getLanguage(), file.getLocation().toString());
				//code  = transformation.addCode(getLanguage(), path.toString());
				code.setFile(file);
				return generateCodeToFile(element, file);
			}
		}
	}

}
